package cn.aixuxi.notebank.controller;

import cn.aixuxi.notebank.authc.JwtToken;
import cn.aixuxi.notebank.constant.DefConstant;
import cn.aixuxi.notebank.dto.UserInputDTO;
import cn.aixuxi.notebank.entity.UserEntity;
import cn.aixuxi.notebank.service.UserService;
import cn.aixuxi.notebank.util.JwtUtils;
import cn.aixuxi.notebank.util.RedisUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 类描述 登录处理Controller
 *
 * @author ruozhuliufeng
 * @version 1.0
 * @date 2020/12/10 21:32
 */
@Controller
@RequestMapping("login")
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 功能描述: 用户登录
     *
     * @param userInputDTO 用户登录信息
     * @param session      存储用户信息
     * @param response     将Token存储到Header中
     * @return : 返回页面
     * @author : ruozhuliufeng
     * @date : 2020/10/24 22:06
     */
    @PostMapping("/login")
    public String login(UserInputDTO userInputDTO, HttpServletResponse response, HttpSession session) {
        // 处理登录
        Subject subject = SecurityUtils.getSubject();
        String token = JwtUtils.sign(userInputDTO.getUsername(), userInputDTO.getPassword());

        // 将Token放到Header中
        response.setHeader(DefConstant.ACCESS_TOKEN, token);
        // 将Token存进Redis中
        redisUtils.set(DefConstant.PREFIX_USER_TOKEN + token, token);
        // 对用户进行登录
        subject.login(new JwtToken(token));
        UserEntity user = userService.findByUsername(JwtUtils.getUsername(token));
        session.setAttribute("user", user);
        return "redirect:/index";
    }

}
